<!--
    by: yuanbiao 2021年06月10日
    name: x-office-viewer
    notes:
-->
<template>
  <div :class="[`${prefixCls}`]">
    <div v-if="suffix==='docx'" ref="docx" :class="[`${prefixCls}__docx`]"></div>
    <!-- <div v-else-if="suffix==='xlsx'" :class="[`${prefixCls}__xlsx`]">
      <xlsx-read :file="filedata">
        <xlsx-table />
      </xlsx-read>
    </div> -->
    <!-- <div v-else-if="suffix==='pptx'" ref="pptx" :class="[`${prefixCls}__pptx`]"></div> -->
    <iframe v-else :class="[`${prefixCls}__default`]" :src="previewUrl"></iframe>
  </div>
</template>

<script>
import Toast from '@/components/toast/index.js'
// import pptxparse from 'pptx-parser'
// import {XlsxRead, XlsxTable} from 'vue-xlsx'

const Docx = require('docx-js')
// const PPTX2HTML = require('pptx2html').default
const axios = require('axios')
const prefixCls = 'x-office-viewer'

export default {
  name: 'x-office-viewer',
  components: {
    // XlsxRead,
    // XlsxTable
  },
  props: {
    options: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      prefixCls: prefixCls,
      officeHost: 'https://view.officeapps.live.com/op/embed.aspx?src=', // 微软官方提供的office预览服务
      filedata: '',
      previewUrl: '',
      suffix: ''
    }
  },
  watch: {
    options: {
      handler (n) {
        this.suffix = ''
        this.$nextTick(() => {
          this.optionsHandler(n)
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    optionsHandler (options) {
      this.suffix = options.label.split('.').pop()
      switch (this.suffix) {
        case 'docx':
          this.getFileData(this.options.url).then((res) => {
            Docx.docx2HTML(res.data).then(docx => {
              docx.toHTML(this.$refs.docx)
            })
          })
          break
        // case 'pptx':
          // this.getFileData(this.options.url).then((res) => {
          //   PPTX2HTML(res.data).then(res => {
          //     console.log(res)
          //   })
          // })
          // this.getFileData(this.options.url).then((res) => {
          //   pptxparse(res.data).then(res => {
          //     console.log(res)
          //   })
          // })
          // break
        // case 'xlsx':
        //   this.getFileData(this.options.url).then((res) => {
        //     this.filedata = res.data
        //   })
        //   break
        default:
          this.previewUrl = `${this.officeHost}${options.url || ''}`
          break
      }
    },
    getFileData (url) {
      this.filedata = ''
      return axios.get(url, { responseType: 'blob' }).catch((err) => {
        let message = (err || {}).message || '未知错误'
        Toast(`发生错误：${message}`)
      })
    }
  }
}
</script>
